<template>
  <div>

  <basic-container>
    <vue-element-loading :active="loading" spinner="bar-fade-scale" color="#409eff" background-color="rgba(255,255,255,0.2)"/>
    <el-form :inline="true">
      <div style="margin-top: 22px">
        <el-form-item>
          <el-input placeholder="模板名称" v-model=" formInline.tmpName " clearable class="input-with-select">
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button icon="el-icon-search" type="primary"  @click="onSubmit">查询</el-button>
          <el-button type="danger" @click="addTmp">增加模板</el-button>
        </el-form-item>
      </div>
    </el-form>
    <el-row>
      <el-col :span="24">
        <template>
          <el-table
            :data="tableData"
            stripe
            style="width: 100%">
            <el-table-column
              width="100"
              prop="actId"
              label="模板ID">
            </el-table-column>
            <el-table-column
              width="250"
              prop="gameName"
              label="游戏">
            </el-table-column>
            <el-table-column
              width="350"
              prop="tmpName"
              label="模版名称">
            </el-table-column>
            <el-table-column
              prop="acInfos"
              label="关联优惠券">
              <template slot-scope="scope">
                <span v-html="scope.row.acInfos"></span>
              </template>
            </el-table-column>

          <el-table-column
            prop="address"
            label="操作"
            width="150">
            <template slot-scope="scope" align="center">
              <div>
                <el-button @click="editClick(scope.row)" type="text" size="medium">修改</el-button>
                <el-button @click="delClick(scope.row.actId)" type="text" size="medium">删除</el-button>
              </div>
            </template>
          </el-table-column>
          </el-table>
        </template>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.currentPage"
          :page-sizes="[10,20, 50, 100, 200]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
      </el-col>
    </el-row>

    <el-dialog :title="mode" :visible.sync="dialogFormVisible" @close="closeDialog()" customClass="customWidth">
      <div v-if="dialogFormVisible">
        <el-form :model="form" label-width="100px" class="demo-ruleForm" ref="ruleForm">
          <el-form-item prop="tmpName" label="模板名称：">
            <el-input v-model="form.tmpName" autocomplete="off" clearable placeholder="模板名称"></el-input>
          </el-form-item>
          <el-form-item prop="url" label="模板备注：">
            <el-input v-model="form.tmpMemo" type="textarea" clearable placeholder="模板备注"></el-input>
          </el-form-item>
          <el-form-item label="游戏：" >
            <span v-if="form.actId != '' " >
              <el-select style="width: 100%" v-model="form.gameProjectId" filterable clearable placeholder="请选择" @click.native="gameSelect" disabled>
              <el-option
                v-for="item in gamelist"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
            </span>
            <span v-if="form.actId == '' " >
              <el-select style="width: 100%" v-model="form.gameProjectId" filterable clearable placeholder="请选择" @click.native="gameSelect">
              <el-option
                v-for="item in gamelist"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
            </span>
          </el-form-item>

          <el-form-item label="优惠档位：" prop="id">
            <el-row style="margin-top: 15px" v-for="(itemList,index) in merchantTakeEffectList" :key="index" >
              <el-col>
                <el-select style="width: 65%" v-model="itemList.id" clearable placeholder="请选择" @click.native="coupon">
                  <el-option
                    v-for="item in couponList"
                    :key="item.id"
                    :label="item.name+'　(优惠券ID：'+item.id+')'"
                    :value="item.id" @click.native="optionCoupon(item.id, itemList)"/>
                </el-select>
                <el-input v-model="itemList.count" @input="reSetAll" onkeyup="value=value.replace(/[^\d]/g,'')" clearable placeholder="数量" style="width: 80px;margin-left: 10px"></el-input>&nbsp;&nbsp;个
                <el-button style="margin-left: 20px" v-if="index==0" type="success" @click="addTakeEffectInput" icon="el-icon-plus"></el-button>
                <el-button style="margin-left: 20px" type="danger" v-if="index>0" @click="delTakeEffectInput(index)" icon="el-icon-minus"></el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="总优惠：">
            <el-input v-model="form.allAmount" readonly @input="reSetAll" onkeyup="value=value.replace(/[^\d]/g,'')" clearable placeholder="数量" style="width: 200px;"></el-input>&nbsp;&nbsp;元
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog()">取 消</el-button>
        <el-button type="primary" @click="addTmpData">确 定</el-button>
      </div>
    </el-dialog>

  </basic-container>
  </div>
</template>

<style>
.input-with-select .el-input-group__prepend {
  background-color: #fff;
  width: 100px;
}
</style>


<script>

import {gamePhoneList,gameList} from "@/api/game/game";
import {getToken} from "@/util/auth";

import {cloneObj, parseParam} from "@/util/util";
import {saveCouponTmp, gamecouponTmpPage,removeGct} from "@/api/app/gamecoupon";
import VueElementLoading from 'vue-element-loading'
import {couponList} from "@/api/system/details";


export default {
  data() {
    return {
      leading:false,
      leadlevel:2,//会长等级
      lead:{},
      page: {
        currentPage: 1,
        pageSize: 20,
        total: '',
      },

      gamelist:[],
      formInline: {
        projectId:'',
        gameId: '',
        tmpName: '',
      },
      gamePra:{ gameProjectId:'',gameId:''},
      form: {
        acId:'',
        gameProjectId:'',
        id:0,
        tmpName: '',
        tmpMemo: '',
        actId:0,
        acIds:[],
        acCounts:[],
        acCouponAmounts:[],
        ids:[],
        allAmount:0
      },
      count:'',
      tableData:[],
      dialogFormVisible:false,
      couponList:[],
      merchantTakeEffectList:[],
    };

  },

  computed: {},
  components: {
    VueElementLoading
  },
  created() {

  },
  mounted() {
    this.onload();
    this.game();
  },
  methods: {
    formatDateTime(timeStamp){
      var date = new Date();
      date.setTime(timeStamp);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? ('0' + m) : m;
      var d = date.getDate();
      d = d < 10 ? ('0' + d) : d;
      return y + '-' + m + '-' + d+' ';
    },
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.onload();
    },
    handleCurrentChange(val) {

      this.page.currentPage = val;
      this.onload();
    },

    game(){
      gameList(this.formInline).then(res => {
        const data = res.data.data;
        this.gamelist = data;
      });
    },
    isNotEmpty(arr) {
      return arr != null && arr.length !== 0
    },
    isEmpty(arr) {
      return !this.isNotEmpty(arr)
    },

    onSubmit() {
      this.page.currentPage=1
      this.onload();
    },

    onload() {
      this.loading = true;
      gamecouponTmpPage(this.page.currentPage, this.page.pageSize, Object.assign(this.formInline)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.tableData = data.records;
        this.loading = false;
      });
    },

    gameSelect(){

    },
    coupon(){
      if(this.form.gameProjectId==''){
        this.$message({
          type: "error",
          message: "请先选择游戏!"
        });
        return;
      }
      this.gamePra.gameProjectId=this.form.gameProjectId
      this.gamePra.gameId=this.form.gameProjectId
      couponList(this.gamePra).then(res => {
        const data = res.data.data;
        console.log("data",data)
        this.couponList = data;
      });
    },

    optionCoupon(val, itemList){
      console.log("val",val)
      for (let i = 0; i < this.couponList.length; i++) {
        if(this.couponList[i].id==itemList.id){
          //alert(this.couponList[i].couponName + "," + itemList.id)
          itemList.count = 1
          itemList.amount = this.couponList[i].amount
          break;
        }
      }
      this.reSetAll()
    },
    addTmp() {
      this.dialogFormVisible = true
      this.mode = '新增'
      this.merchantTakeEffectList.push({'id': '', 'custname':'', 'count':'', 'amount':0})
    },
    delClick(actId){
      this.$confirm("确定发要删除该模板？", '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeGct(actId).then(res => {
          if(res.data.success){
            this.$message({
              message: '删除成功！',
              type: 'success'
            });
            this.onload()
          }else{
            this.$message({
              message: res.data.msg,
              type: 'warning'
            });
          }
        });
      }).catch(() => {
      });
    },
    editClick(bean) {
      this.dialogFormVisible = true
      this.mode = '编辑'
      let ids = bean.idsT.split(";");
      let acIds = bean.acIdsT.split(";");
      let acCouponAmounts = bean.acCouponAmountsT.split(";");
      let acCounts = bean.acCountsT.split(";");
      this.form.ids = ids;
      this.form.actId = bean.actId;
      this.form.id = bean.id;
      this.form.tmpName = bean.tmpName;
      this.form.tmpMemo = bean.tmpMemo;
      this.form.gameProjectId = bean.gameProjectId;
      this.gamePra.gameProjectId = this.form.gameProjectId
      this.gamePra.gameId=this.form.gameProjectId
      couponList(this.gamePra).then(res => {
        const data = res.data.data;
        console.log("data",data)
        this.couponList = data;
        for(let i=0; i<ids.length; i++) {
          this.merchantTakeEffectList.push({'id': parseInt(acIds[i]), 'custname':'', 'count':acCounts[i], 'amount':acCouponAmounts[i]})
        }
        this.reSetAll()
      });
    },
    addTmpData(){
      if(this.form.tmpName.trim() == '') {
        this.$message({
          type: "error",
          message: "请输入模板名称!"
        });
        return
      }
      if(this.form.gameProjectId==''){
        this.$message({
          type: "error",
          message: "请先选择游戏!"
        });
        return;
      }
      if(this.merchantTakeEffectList.length <= 0 || this.merchantTakeEffectList.length > 0 && this.merchantTakeEffectList[0].amount <= 0){
        this.$message({
          type: "error",
          message: "请选择优惠卷档位！!"
        });
        return;
      }
      this.form.acIds = []
      this.form.acCounts = []
      this.form.acCouponAmounts = []
      for(let i = 0; i < this.merchantTakeEffectList.length; i++) {
        this.form.acIds.push(this.merchantTakeEffectList[i].id);
        this.form.acCounts.push(this.merchantTakeEffectList[i].count);
        this.form.acCouponAmounts.push(this.merchantTakeEffectList[i].amount);
      }
      saveCouponTmp(this.form).then(res => {
        if (res.data.success) {
          this.$message({
            type: "success",
            message: res.data.msg
          });
          this.form = {
            gameProjectId:'',
            acId:'',
            id:0,
            tmpName: '',
            tmpMemo: '',
            actId:0,
            acIds:[],
            acCounts:[],
            acCouponAmounts:[],
            allAmount:0
          };
          this.gamePra={ gameProjectId:'',gameId: ''};
          this.merchantTakeEffectList=[];
          this.couponList=[];
          this.dialogFormVisible = false;
          this.onload();
        } else {
          this.$message({
            type: "error",
            message: res.data.msg
          });
        }
      });
    },

    reSetAll(){
      let allAmount = 0;
      for(let i = 0; i<this.merchantTakeEffectList.length; i++) {
        allAmount += this.merchantTakeEffectList[i].amount/100 * this.merchantTakeEffectList[i].count
      }
      this.form.allAmount = allAmount;
    },
    addTakeEffectInput() {
      this.merchantTakeEffectList.push({'id': '', 'custname':'', 'count':'', 'amount':0})
    },
    delTakeEffectInput(index) {
      console.log(index)
      this.merchantTakeEffectList.splice(index, 1)
      this.reSetAll()
    },

    closeDialog() {
      this.form = {
          gameProjectId:'',
          acId:'',
          id:0,
          tmpName: '',
          tmpMemo: '',
          actId:0,
          acIds:[],
          acCounts:[],
          acCouponAmounts:[],
          allAmount:0
      };
      this.gamePra={ gameProjectId:'', gameId: ''};
      this.merchantTakeEffectList=[];
      this.couponList=[];
      this.dialogFormVisible = false;

    },
  }
}

</script>

<style>
.customWidth {
  width: 45%;
  background-color: #FFFFFF !important;
}
</style>
